package study.cell_game.activity;

import org.andengine.engine.camera.Camera;
import org.andengine.engine.handler.IUpdateHandler;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.andengine.entity.scene.IOnSceneTouchListener;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.scene.menu.MenuScene;
import org.andengine.entity.scene.menu.MenuScene.IOnMenuItemClickListener;
import org.andengine.entity.scene.menu.item.IMenuItem;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.text.Text;
import org.andengine.entity.text.TextOptions;
import org.andengine.entity.util.FPSLogger;
import org.andengine.input.touch.TouchEvent;
import org.andengine.opengl.font.Font;
import org.andengine.opengl.font.FontFactory;
import org.andengine.ui.activity.SimpleBaseGameActivity;
import org.andengine.util.HorizontalAlign;
import org.andengine.util.color.Color;

import study.cell_game.objects.AIPlayer;
import study.cell_game.objects.Cell;
import study.cell_game.objects.CellMap;
import study.cell_game.objects.Player;
import study.cell_game.objects.Textures;
import study.cell_game.objects.textures.MainMenuTextures;
import study.cell_game.objects.textures.TokenTextures;
import study.cell_game.objects.tokens.Token;
import study.cell_game.scenes.GameScene;
import study.cell_game.scenes.MainMenuScene;
import android.graphics.Typeface;
import android.util.DisplayMetrics;
import android.view.KeyEvent;

public class GameActivity extends SimpleBaseGameActivity implements IOnMenuItemClickListener {

	  private static final int CAMERA_WIDTH = 800;
	  private static final int CAMERA_HEIGHT = 480;
	  
	  public static Camera mCamera;
	  public static Textures mTextures;
	  public static MainMenuTextures menuTextures;
	  public static GameActivity main;
	  private static int timer =0;
	  
	  private MenuScene mainMenuScene;
	  private GameScene gameScene;
	
	  private Font mFont;
	  private Font bigFont;
	  public Font getFont(){
		  return mFont;
	  }
	@Override
	public EngineOptions onCreateEngineOptions() {
		main = this;
		this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
	    final EngineOptions options = new EngineOptions(true,
	        ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(
	            getScreenResolutionRatio()), this.mCamera);
	    int interval = 5;
        options.getTouchOptions().setTouchEventIntervalMilliseconds(interval);
	    return options;
	}

	@Override
	protected void onCreateResources() {
		this.mFont = FontFactory.create(this.getFontManager(), this.getTextureManager(), 256, 256, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 32, Color.RED.getABGRPackedInt());
				//FontFactory.create(this.getFontManager(), null, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 32, true, Color.RED):
				// create(this.getFontManager(), 256, 256, 32, true, Color.RED);
//FontFactory.create(this.getFontManager(), this.getTextureManager(), 256, 256, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 32);
		this.bigFont = FontFactory.create(this.getFontManager(), this.getTextureManager(), 480, 480, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 100, Color.RED.getABGRPackedInt());
			
		this.mFont.load();
		menuTextures = MainMenuTextures.getInstance(this, getEngine());
		mTextures = new Textures(this, getEngine());
		TokenTextures.getInstance(this, getEngine());
	}

	@Override
	protected Scene onCreateScene() {
		this.mEngine.registerUpdateHandler(new FPSLogger());
		this.mainMenuScene = new MainMenuScene(mCamera, mEngine, this, menuTextures); 
		this.gameScene = GameScene.getInstance();
	    return this.mainMenuScene; 
	}
	
	private float getScreenResolutionRatio() {
	    DisplayMetrics dm = new DisplayMetrics();
	    getWindowManager().getDefaultDisplay().getMetrics(dm);
	    return ((float) dm.widthPixels) / ((float) dm.heightPixels);
	  }
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		/*if(keyCode == KeyEvent.KEYCODE_BACK)
		{
			if(!GameLoad) return true;
			if(GameLoad && MScene != null)
			{
				MScene.KeyPressed(keyCode, event);
				return true;
			}
			return true;
		}*/
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public boolean onMenuItemClicked(MenuScene pMenuScene, IMenuItem pMenuItem, float pMenuItemLocalX,
			float pMenuItemLocalY) {
		handleButtonActions();
	    
	    switch(pMenuItem.getID())
	    {	
	    	case MainMenuScene.OPTIONS_BUTTON:
	        	//this is currently unavailable
	    		return true;
	    	case MainMenuScene.LOAD_BUTTON:
	            // this is currently unavailable
	    		//action
	            return true;
	    	case MainMenuScene.QUIT_BUTTON:
	            this.finish();
	            return true;
	    	case MainMenuScene.PLAY_BUTTON:
	    		this.mEngine.setScene(gameScene);//action
	    		final Player p = Player.getInstance();
	    		final AIPlayer ai = AIPlayer.getInstance();
	    		gameScene.registerUpdateHandler(new IUpdateHandler() {                    
	                public void reset() {        
	                }             
	                private boolean end = false;
		    		
	                public void onUpdate(float pSecondsElapsed) {
	                	
	                	if(timer==100 && !end) {
	                		long updateCount = 0;
	                		updateCount++;
	                		p.update();
	                		//p.postUpdate();
	                		//ai.update();
	                		timer=0;
	                		
	                		
	                		end = true;
	                		study.cell_game.enums.PlayerColor owner = null;
	                		for(int i=0; i < gameScene.getMap().getCellNum(); i++){
	                			Cell c = gameScene.getMap().getCell(i);
	                			if(owner == null){
	                				if(c.getToken()!=null){
	                					owner = c.getToken().getOwner();
	                				} else {
	                					end = false;
	                					break;
	                				}
	                			} else {
	                				if(c.getToken()==null ||  c.getToken().getOwner() != owner){
	                					end = false;
	                					break;
	                				}
	                			}
	                			
	                		}
	                		
	                		if(owner == null){
	                			end = false;
	                		}
	                		
	                		if(end){
	                			String text;
	                			if (owner == study.cell_game.enums.PlayerColor.BLUE){
	                				text = "WIN";
	                			} else {
	                				text = "LOSE";
	                			}
	                			
	                			Text centerText = new Text(350, 200, bigFont, text, new TextOptions(HorizontalAlign.CENTER),
	                					GameActivity.main.getVertexBufferObjectManager());
	                			
	                			gameScene.getOverlayLayer().attachChild(centerText);
	                		}
	                	}
	                	timer++;
	                }
	            });
	    		
	        	return true;
	            
	        default:
	            return false;
	    }
	}

	private void handleButtonActions() {
		// TODO Auto-generated method stub
		
	}
}
